package cn.edu.hit.kg.entity;

import cn.edu.hit.ObjectCacheUtils;
import cn.edu.hit.kg.data.GraphData;
import cn.edu.hit.kg.data.Node;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//import cn.edu.hit.kg.NeoDriver;
//import org.neo4j.driver.v1.Record;
//import org.neo4j.driver.v1.types.Node;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

//import static org.neo4j.driver.v1.Values.parameters;

public class Component extends BaseNode {
    static Logger logger = LoggerFactory.getLogger(Component.class);

    public Component(Node node) {
        super(node);
    }

    public static ObjectCacheUtils<String, Map> componentCache = new ObjectCacheUtils<>(Component::loadComponentByName);

    public static Map getByName(String name) {
        Map result = componentCache.get(name);
        if (result == null) {
            return Collections.singletonMap("name", name);
        }
        return result;
    }

    private static Map loadComponentByName(String name) {
        GraphData graphData = GraphData.getInstance();
        Optional<Node> optional = graphData.getIdSetByLabel("Component").stream().map(graphData::getById)
                .filter(node -> StringUtils.equals(name, node.get("name").toString()) ||
                        StringUtils.equals(name, escapeText(node.get("name").toString()))).findAny();
        if (optional.isPresent()) {
            Node component = optional.get();
            Map<String, Object> map = new HashMap<>(component.asMap());
            long id = component.id();
            map.put("id", id);
            return map;
        } else {
            logger.error("In Component.java,loadComponentByName,Cannot find Component called '" + name + "'");
//            System.err.println("In Component.java,loadComponentByName,Cannot find Component called '"+name+"'");
            return null;
        }
//        try (NeoDriver driver = new NeoDriver()){
//            Record record = driver.query("match (n:Component) where n.name=$name or n.name=$nname return n ",
//                    parameters("name",name,"nname",escapeText(name))).single();
//            Node node = record.get("n").asNode();
//            Map map = new HashMap(node.asMap());
//            long id  = node.id();
//            map.put("id",id);
//            return map;
//        }catch (org.neo4j.driver.v1.exceptions.NoSuchRecordException e){
//            e.printStackTrace();
//            System.err.println("In Component.java,loadComponentByName,Cannot find Component called '"+name+"'");
//            return null;
//        }
    }

    public static void main(String[] args) {
        Map map = getByName("定子汽端铁芯");
        System.out.println(map);
//        System.out.println(escapeText("定子汽端铁芯"));
    }
}
